package com.nineclock.auth.intergration.processor.impl;

import cn.hutool.core.util.StrUtil;
import com.nineclock.auth.intergration.entity.IntergrationAuthenticationEntity;
import com.nineclock.auth.intergration.exception.NcOAuth2Exception;
import com.nineclock.auth.intergration.processor.AuthenticationProcessor;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 手机号-验证码 处理器
 */
@Component
public class SmsAuthenticationProcessor implements AuthenticationProcessor {

    @Autowired
    private SysUserFeign sysUserFeign;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public Boolean support(IntergrationAuthenticationEntity entity) {
        if(entity != null && "sms".equals(entity.getAuthType())){
            return true;
        }
        return false;
    }


    @Override
    public SysUserDTO authenticate(IntergrationAuthenticationEntity entity) {
        //获取参数
        String mobile = entity.getAuthParameter("mobile");//手机号
        String password = entity.getAuthParameter("password"); //验证码

        //校验
        if(StrUtil.isEmpty(mobile) || StrUtil.isEmpty(password)){
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //获取手机号对应的用户信息
        SysUserDTO userDTO = sysUserFeign.query(mobile).getData();
        if(userDTO == null){
            throw new NcException(ResponseEnum.USER_NOT_REGISTER);
        }


        //组装并返回
        /*//TODO 验证码目前先固定为1234 , 后续完善;
        if("1234".equals(password)){ //通过 , 返回
            userDTO.setPassword(passwordEncoder.encode(password)); //设置验证, 验证码进行匹配
            return userDTO;
        }else{
            throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
        }*/


        //获取正确的验证--> redis
        String key = SMSConstant.SMS_LOGIN_KEY_PREFIX + mobile;
        String realCode = redisTemplate.boundValueOps(key).get();

        if(StrUtil.isNotEmpty(realCode) && realCode.equals(password)){ //验证通过
            userDTO.setPassword(passwordEncoder.encode(password)); //设置验证, 验证码进行匹配
            return userDTO;
        }else{
            throw new NcOAuth2Exception(ResponseEnum.CODE_IMAGE_ERROR.getMessage());
        }

    }
}
